import { getToken, tokenKey } from "@/utils/cache";
import axios from "axios";
import store from "@/store";
import setting from "@/setting";
const instance = axios.create({
  baseURL: setting.BASE_URL,
  timeout: 900000,
  headers: {
    "Content-type": "application/json",
  },
});

/**
 * @see 错误处理
 */
async function error(error) {
  console.log(error, "接口错误 error");
  if (error.message === "timeout of 30000ms exceeded") {
    let str = "请求超时,请稍后再试";
    return Promise.reject(str);
  } else if (error.message === "Network Error") {
    let str = "无法访问到服务器,请联系相关管理员";
    return Promise.reject(str);
  } else if (error.message === "Request failed with status code 404") {
    return Promise.reject("接口访问失败");
  } else if (error.message.indexOf("Access-Control-Allow-Origin") !== -1) {
    return Promise.reject("出现跨域错误,请联系相关管理员");
  }
  return Promise.reject(error.message);
}

/**
 * @see 请求拦截
 */
instance.interceptors.request.use((config) => {
  // 这里可以携带header
  if (!config.headers[tokenKey]) {
    config.headers[tokenKey] = getToken();
  }
  return config;
}, error);

/**
 * @see 响应拦截
 */
instance.interceptors.response.use(async (res) => {
  // 这里可以做响应拦截
  const { errcode, errmsg, result } = res.data;
  // console.log(res,'这里可以做响应拦截')
  if (
    res.request.responseType === "arraybuffer" ||
    res.request.responseType === "blob"
  ) {
    return Promise.resolve(res);
  }
  if (
    res.headers["content-type"] &&
    res.headers["content-type"].indexOf("image") !== -1
  ) {
    return Promise.resolve(res.data);
  }
  switch (errcode) {
    case "0":
      return Promise.resolve(result);
    case "1":
      return Promise.resolve({ data: [] });
    case "1000":
      return Promise.resolve(errmsg);
    case "1001":
      return Promise.reject(errmsg);
    case "9000":
      return Promise.reject(
        errmsg + " 暂无数据，请联系相关人员处理或重新选择文件申请"
      );
    case "-1100":
      return Promise.reject(errmsg);
    case "-2002":
      return Promise.reject(errmsg);
    case "-3000":
      return Promise.reject(errmsg);
    default:
      return Promise.resolve(res.data);
  }
}, error);
const request = (config) => {
  config.data = config.data || config.params || {};
  // 混入参数
  const { schoolCode } = store.getters.schoolConfig;
  const { userId } = store.getters.userInfo;
  if (schoolCode && !config.data.schoolCode) {
    config.data.schoolCode = schoolCode;
  }
  if (
    userId &&
    config.data.schoolCode &&
    !config.data.userId 
  ) {
    config.data.userId = userId;
  }
  return instance(config);
};
export default request;
